package com.zyg.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.zyg.manager.entity.SpecificationEntity;
import com.zyg.manager.entity.SpecificationOptionEntity;
import com.zyg.manager.service.SpecificationOptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.utils.PageUtils;
import com.zyg.common.utils.Query;

import com.zyg.manager.dao.TypeTemplateDao;
import com.zyg.manager.entity.TypeTemplateEntity;
import com.zyg.manager.service.TypeTemplateService;


@Service("typeTemplateService")
public class TypeTemplateServiceImpl extends ServiceImpl<TypeTemplateDao, TypeTemplateEntity> implements TypeTemplateService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SpecificationOptionService optionService;
    //分页条件查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<TypeTemplateEntity> wrapper = new QueryWrapper<>();
        Object key = params.get("key");
        if (key!=null){
            wrapper.like("id",key)
                   .or()
                   .like("name",key);
        }
        IPage<TypeTemplateEntity> page = this.page(
                new Query<TypeTemplateEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //查询所有的模板
    @Override
    public List<TypeTemplateEntity> findAll() {
        List<TypeTemplateEntity> list = this.list();
        for (TypeTemplateEntity entity : list) {
            //1、放品牌列表到redis
            //得到模板id
            String id = entity.getId();
            //得到模板的品牌列表字符串
            String brandIds = entity.getBrandIds();
            //以模板id为key，以品牌列表为值放到redis中
            redisTemplate.boundHashOps("brandList").put(id,brandIds);

            //2、放规格列表
            //得到规格列表
            String specIds = entity.getSpecIds();
            //转换为List<Map>格式
            List<Map> maps = JSON.parseArray(specIds, Map.class);
            for (Map map : maps) {
                Object specId = map.get("id");
                List<SpecificationOptionEntity> options = optionService.list(new QueryWrapper<SpecificationOptionEntity>().eq("spec_id", specId));
                map.put("options",options);
            }
            //转化为json串并放到redis中
            redisTemplate.boundHashOps("specList").put(id,JSON.toJSONString(maps));
        }
        return list;
    }

}